﻿using System;
using System.Collections.Generic;
using System.Linq;
using Viettel.VOFFICE.DAO.Models;

namespace Viettel.VOFFICE.DAO.DAL.Repository
{
    /// <summary>
    /// việc phải làm trong một node
    /// </summary>
    public class TodoRepository : IRepository<Todo>
    {
        private VOFFICEContext context;

        public TodoRepository(VOFFICEContext context)
        {
            if (context == null)
            {
                throw new Exception("Context must be init");
            }
            this.context = context;
        }
        public IEnumerable<Todo> Get()
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Todo GetById(object id)
        {
            var findId = int.Parse(id.ToString());
            return context.Todos.FirstOrDefault(o => o.Id == findId);
        }

        public IEnumerable<Todo> FindByName(object s)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="T"></param>
        public void Insert(Todo T)
        {
            if (null != T)
            {
                context.Todos.Add(T);
                Save();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        public void Delete(object id)
        {
            var item = GetById(id);
            if (null != item)
            {
                Delete(item);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="T"></param>
        public void Delete(Todo T)
        {
            if (null != T)
            {
                context.Todos.Attach(T);
                context.Todos.Remove(T);
                Save();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="T"></param>
        public void Update(Todo T)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 
        /// </summary>
        public void Save()
        {
            context.SaveChanges();
        }

        /// <summary>
        /// Xóa tất cả các công việc trong bởi node_id truyền vào
        /// </summary>
        /// <param name="nodeId"></param>
        public void DeleteByNode(int nodeId)
        {
            context.Todos.Where(o => o.NodeId == nodeId).ToList().ForEach(t =>
                {
                    context.Todos.Attach(t);
                    context.Todos.Remove(t);
                });
            Save();
        }
    }
}
